package dao

import (
	"fmt"
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zlog"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type BlockInfo struct {
	Id     string `gorm:"column:id;primary"`
	RoleId int64  `gorm:"column:role_id"`
	MapId      int32                      `gorm:"column:map_id"`
	BlockIdArr datatypes.JSONSlice[int32] `gorm:"column:block_id_arr"`
	FogIndex   int32                      `gorm:"column:fog_index"`
}

//type BuildInfo struct {
//	BuildID int32
//	BuildIndex int32
//	BuildLv int32
//	BuildPosX int32
//	BuildPosZ int32
//}

func (BlockInfo) TableName() string {
	return "block_info"
}

var (
	all_block_info_field = util.GetGormFields(BlockInfo{})
)

func GetBlockInfoByKey(key string) *BlockInfo {
	db := mysql.GetServerDBConnection()
	var blockInfo BlockInfo
	if err := db.Select(all_block_info_field).Where("Id=?", key).First(&blockInfo).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetBlockInfoByKey ERR!!! Id: %s, err: %v", key, err)
		}
		return nil
	}
	return &blockInfo
}

func UpdateBlockInfoByKey(key string, changeField *map[string]any) {
	db := mysql.GetServerDBConnection()
	if err := db.Model(BlockInfo{}).Where("Id=?", key).Updates(changeField).Error; err != nil {
		zlog.Errorf("UpdateBlockInfoByKey %s data failed: %v", key, err)
	}
}

func NewBlockInfoData(blockArr []int32, fogIndex int32, roleId int64, mapId int32) {
	blockInfoObj := &BlockInfo{
		Id:         fmt.Sprint(roleId) + "-" + fmt.Sprint(mapId),
		RoleId:     roleId,
		MapId:      mapId,
		BlockIdArr: blockArr,
		FogIndex:   fogIndex,
	}

	db := mysql.GetServerDBConnection()
	if err := db.Create(blockInfoObj).Error; err != nil {
		zlog.Errorf("create blockInfo %v data failed: %v", blockInfoObj, err)
	}
}
